import React from 'react';
import PropTypes from 'prop-types';
import {View, Text, StyleSheet, TouchableOpacity} from 'react-native';
import tfa from '../library/2fa';

class Tfa extends React.PureComponent {

  static defaultProps = {
    len: 6,
    ts: 30,
    algo: 'SHA1',
    onRemove: () => {},
  };

  static propTypes = {
    len: PropTypes.number,
    ts: PropTypes.number,
    algo: PropTypes.string,
    secret: PropTypes.string.isRequired,
    site: PropTypes.string.isRequired,
    email: PropTypes.string.isRequired,
    onRemove: PropTypes.func.isRequired,
  };

  constructor(props) {
    super(props);
    this.tfa = new tfa(this.props.len, this.props.ts, this.props.algo);
    const refreshTime = this.tfa.refreshTime();
    const percent = refreshTime * 100 / this.props.ts;
    this.state = {
      code: this.tfa.getCode(this.props.secret),
      refreshTime: refreshTime,
      percent: this.tfa.refreshTime() * 100 / this.props.ts,
      backgroundColor: this.getBackgroundColor(percent),
    };
  }

  componentDidMount() {
    this.interval = setInterval(this.refreshCode, 1000);
  }

  componentWillUnmount() {
    this.interval && clearTimeout(this.interval);
  }

  refreshCode = () => {
    const refreshTime = this.tfa.refreshTime();
    const percent = refreshTime * 100 / this.props.ts;
    this.setState({
      code: this.tfa.getCode(this.props.secret),
      refreshTime: refreshTime,
      percent: percent,
      backgroundColor: this.getBackgroundColor(percent),
    });
  };

  getBackgroundColor = (percent) => {
    if (percent >= 75) {
      return '#9AFF02';
    }
    if(percent >= 50) {
      return '#EAC100';
    }
    if(percent >= 25) {
      return '#FF9224';
    }
    return '#FF5809';
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.wrapper}>
          <View>
            <Text>{this.props.site}:{this.props.email}</Text>
            <Text style={styles.code}>{this.state.code}</Text>
          </View>
          <View>
            <TouchableOpacity onPress={() => {this.props.onRemove(this.props.id)}}><Text style={styles.delBtn}>删除</Text></TouchableOpacity>
          </View>
        </View>
        <View>
          <View style={{width: this.state.percent + '%', height: 3, backgroundColor: this.state.backgroundColor}} />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'white',
    marginBottom: 10,
  },
  delBtn: {
    color: 'red',
  },
  wrapper: {
    paddingLeft: 14,
    paddingTop:10,
    paddingRight: 14,
    paddingBottom: 10,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  code: {
    fontSize: 30,
    fontWeight: '800',
    color: 'black',
    marginTop: 6,
  },
});


export default Tfa;